<template>
  <div class="order-page">
    <div class="container">
      <!-- 页面标题 -->
      <div class="page-header">
        <h1 class="page-title">我的訂單</h1>
        <div class="page-subtitle">查看和管理您的所有訂單</div>
      </div>


      <!-- 订单列表 -->
      <div class="order-list">
        <div v-if="loading" class="loading-container">
          <el-skeleton :rows="3" animated />
        </div>

        <div v-else-if="filteredOrders.length === 0" class="empty-state">
          <el-empty description="暂无訂單" :image-size="200">
            <el-button type="primary" @click="goShopping">去购物</el-button>
          </el-empty>
        </div>

        <div v-else class="orders">
          <div
            v-for="order in filteredOrders"
            :key="order.id"
            class="order-item"
          >
            <!-- 订单头部 -->
            <div class="order-header">
              <div class="order-info">
                <span class="order-number">訂單號：{{ order.OrdersNumber }}</span>
                <span class="order-date">{{ order.OrdersTime }}</span>
              </div>
              <div class="order-status">
                <el-tag :type="getStatusType(order.ShipmentState)">
                  {{ order.ShipmentState }}
                </el-tag>
              </div>
            </div>

            <!-- 订单產品 -->
            <div class="order-products">
              <div
                v-for="item in order.ListCart"
                :key="item.Id"
                class="product-item"
              >
                <div class="product-image">
                  <img :src="getImageUrl(item.PicUrls)" :alt="item.GoodsName" />
                </div>
                <div class="product-info">
                  <h3 class="product-name">{{ item.GoodsName }}</h3>
                  <div class="product-spec">產品ID: {{ item.GoodsId }}</div>
                  <div class="product-sku" v-if="item.SKUDatas">
                    <el-tag size="small" type="primary">{{ item.SKUDatas.title }}</el-tag>
                    <span class="sku-price">(<Currency/>{{ formatPrice(item.SKUDatas.price) }})</span>
                  </div>
                  <div class="product-price"><Currency/>{{ formatPrice(item.Pirce) }}</div>
                </div>
                <div class="product-quantity">x{{ item.BuyQty }}</div>
              </div>
            </div>

            <!-- 订单底部 -->
            <div class="order-footer">
              <div class="order-total">
                <span class="total-label">實付款：</span>
                <span class="total-amount"><Currency/>{{ formatPrice(order.CartTotal) }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { fetchSearch } from "@/request/req.ts"
import { commonStore } from '@/store/common.ts'
import { formatPrice } from '@/utils/formatPrice.ts'
import Currency from "@/components/common/Currency.vue";

const router = useRouter()
const route = useRoute()
const common = commonStore()

// 响应式数据
const loading = ref(false)
const activeTab = ref('all')
const orders = ref<any[]>([])

// 计算属性
const filteredOrders = computed(() => {
  if (activeTab.value === 'all') {
    return orders.value
  }
  return orders.value.filter(order => getStatusKey(order.ShipmentState) === activeTab.value)
})

const serverUrl = computed(() => {
  const item = common.getItemById(1)
  return item?.value
})

const orderId = computed(() => route.query.keyword as string || '')


/**
 * 获取订单数据
 */
const getOrders = async () => {
  if (!orderId.value.trim()) {
    // 如果没有订单ID，显示空状态
    orders.value = []
    return
  }

  loading.value = true
  try {
    const res = await fetchSearch({ t: 'DD', k: orderId.value })

    if (res && res.OrdersNumber) {
      orders.value = [res]
    } else {
      orders.value = []
    }
  } catch (error) {
    console.error('获取订单失败:', error)
    orders.value = []
    ElMessage.error('获取訂單失败')
  } finally {
    loading.value = false
  }
}

/**
 * 获取图片完整URL
 */
const getImageUrl = (picUrl: string) => {
  if (!picUrl) return
  return `${serverUrl.value}${picUrl}`
}

/**
 * 获取状态对应的key
 */
const getStatusKey = (status: string) => {
  const statusMap: Record<string, string> = {
    '未付款': 'pending',
    '已付款': 'paid',
    '未發貨': 'paid',
    '已发货': 'shipped',
    '已完成': 'completed',
    '已取消': 'cancelled'
  }
  return statusMap[status] || 'all'
}

const getStatusType = (status: string) => {
  const statusMap: Record<string, string> = {
    '未付款': 'warning',
    '已付款': 'info',
    '未發貨': 'info',
    '已发货': 'primary',
    '已完成': 'success',
    '已取消': 'danger'
  }
  return statusMap[status] || 'info'
}

const goShopping = () => {
  router.push('/')
}

watch(
  () => route.query.keyword,
  (newKeyword, oldKeyword) => {
    if (newKeyword !== oldKeyword) {
      getOrders()
    }
  },
  { immediate: false }
)

onMounted(() => {
  getOrders()
})
</script>

<style scoped>
.order-page {
  background: var(--bg-tertiary);
  min-height: 100vh;
  padding: var(--spacing-xl) 0;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 var(--spacing-xl);
}

/* 页面标题 */
.page-header {
  background: var(--gradient-bg-primary);
  padding: var(--spacing-2xl);
  border-radius: var(--radius-xl);
  margin-bottom: var(--spacing-2xl);
  box-shadow: var(--shadow-medium);
  border: 1px solid var(--border-primary);
}

.page-title {
  font-size: var(--font-size-3xl);
  font-weight: var(--font-weight-bold);
  color: var(--text-primary);
  margin-bottom: var(--spacing-sm);
}

.page-subtitle {
  font-size: var(--font-size-sm);
  color: var(--text-secondary);
}

/* 订单筛选 */
.order-filter {
  background: var(--gradient-bg-primary);
  border-radius: var(--radius-xl);
  margin-bottom: var(--spacing-2xl);
  box-shadow: var(--shadow-medium);
  border: 1px solid var(--border-primary);
  overflow: hidden;
}

/* 自定义标签页样式 */
.order-filter :deep(.el-tabs__header) {
  margin: 0;
  background: transparent;
}

.order-filter :deep(.el-tabs__nav-wrap) {
  padding: 0 20px;
}

.order-filter :deep(.el-tabs__nav) {
  border: none;
}

.order-filter :deep(.el-tabs__item) {
  color: var(--text-primary);
  font-weight: var(--font-weight-medium);
  border: none;
  padding: 0 var(--spacing-xl);
  height: 50px;
  line-height: 50px;
  transition: var(--transition-all);
}

.order-filter :deep(.el-tabs__item:hover) {
  color: var(--primary-color);
}

.order-filter :deep(.el-tabs__item.is-active) {
  color: var(--primary-color);
  font-weight: var(--font-weight-semibold);
}

.order-filter :deep(.el-tabs__active-bar) {
  background-color: var(--primary-color);
  height: 3px;
}

.order-filter :deep(.el-tabs__content) {
  display: none;
}

/* 订单列表 */
.order-list {
  margin-bottom: var(--spacing-2xl);
}

.loading-container {
  background: var(--gradient-bg-primary);
  border-radius: var(--radius-xl);
  padding: var(--spacing-2xl);
  box-shadow: var(--shadow-medium);
  border: 1px solid var(--border-primary);
}

.empty-state {
  background: var(--gradient-bg-primary);
  border-radius: var(--radius-xl);
  padding: var(--spacing-4xl);
  text-align: center;
  box-shadow: var(--shadow-medium);
  border: 1px solid var(--border-primary);
}

.orders {
  display: flex;
  flex-direction: column;
  gap: var(--spacing-xl);
}

.order-item {
  background: var(--gradient-bg-primary);
  border-radius: var(--radius-xl);
  overflow: hidden;
  box-shadow: var(--shadow-medium);
  border: 1px solid var(--border-primary);
  transition: var(--transition-all);
}

.order-item:hover {
  transform: translateY(-2px);
  box-shadow: var(--shadow-strong);
  border-color: var(--primary-color);
}

/* 订单头部 */
.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: var(--spacing-lg) var(--spacing-xl);
  background: var(--gradient-bg-secondary);
  border-bottom: 1px solid var(--border-secondary);
}

.order-info {
  display: flex;
  flex-direction: column;
  gap: var(--spacing-xs);
}

.order-number {
  font-size: var(--font-size-base);
  font-weight: var(--font-weight-semibold);
  color: var(--text-primary);
}

.order-date {
  font-size: var(--font-size-xs);
  color: var(--text-secondary);
}

/* 订单產品 */
.order-products {
  padding: var(--spacing-xl);
}

.product-item {
  display: flex;
  align-items: center;
  gap: var(--spacing-lg);
  padding: var(--spacing-md) 0;
  border-bottom: 1px solid var(--border-secondary);
}

.product-item:last-child {
  border-bottom: none;
}

.product-image {
  width: 80px;
  height: 80px;
  border-radius: var(--radius-lg);
  overflow: hidden;
  flex-shrink: 0;
  border: 1px solid var(--border-secondary);
}

.product-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.product-info {
  flex: 1;
}

.product-name {
  font-size: var(--font-size-base);
  font-weight: var(--font-weight-semibold);
  color: var(--text-primary);
  margin-bottom: var(--spacing-xs);
  line-height: 1.4;
}

.product-spec {
  font-size: var(--font-size-xs);
  color: var(--text-secondary);
  margin-bottom: var(--spacing-sm);
}

.product-sku {
  display: flex;
  align-items: center;
  gap: var(--spacing-sm);
  margin-bottom: var(--spacing-sm);
}

.product-sku .el-tag {
  background: var(--gradient-primary);
  border-color: var(--primary-color);
  color: var(--text-light);
}

.sku-price {
  font-size: var(--font-size-xs);
  color: var(--text-secondary);
  font-weight: var(--font-weight-medium);
}

.product-price {
  font-size: var(--font-size-base);
  font-weight: var(--font-weight-semibold);
  color: var(--primary-color);
}

.product-quantity {
  font-size: var(--font-size-sm);
  color: var(--text-secondary);
  min-width: 40px;
  text-align: right;
}

/* 订单底部 */
.order-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: var(--spacing-lg) var(--spacing-xl);
  background: var(--gradient-bg-secondary);
  border-top: 1px solid var(--border-secondary);
}

.order-total {
  display: flex;
  align-items: center;
  gap: var(--spacing-sm);
}

.total-label {
  font-size: var(--font-size-sm);
  color: var(--text-secondary);
}

.total-amount {
  font-size: var(--font-size-lg);
  font-weight: var(--font-weight-bold);
  color: var(--primary-color);
}

@media (max-width: 768px) {
  .container {
    padding: 0 var(--spacing-lg);
  }

  .page-header {
    padding: var(--spacing-xl);
  }

  .page-title {
    font-size: var(--font-size-2xl);
  }

  .order-filter :deep(.el-tabs__nav-wrap) {
    padding: 0 var(--spacing-lg);
  }

  .order-filter :deep(.el-tabs__item) {
    padding: 0 var(--spacing-md);
    font-size: var(--font-size-sm);
  }

  .order-header {
    flex-direction: column;
    align-items: flex-start;
    gap: var(--spacing-md);
  }

  .order-footer {
    flex-direction: column;
    align-items: flex-start;
    gap: var(--spacing-lg);
  }

  .product-item {
    flex-direction: column;
    align-items: flex-start;
    gap: var(--spacing-md);
  }

  .product-image {
    width: 100%;
    height: 200px;
  }

  .product-quantity {
    text-align: left;
  }
}
</style>
